package data;

import database.DataBaseConnection;
import net.sf.json.JSONObject;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Set;

public class CountLogData {
    public String countData() {
        JSONObject jsonObject = new JSONObject();
        HashMap<String, String> hashMap = new HashMap<>();
        Connection connection = DataBaseConnection.getConnection();
        if (connection != null) {
            String sql1 = "select * from exception";
            ResultSet resultSet1 = DataBaseConnection.query(connection, sql1);
            try {
                while (resultSet1 != null && resultSet1.next()) {
                    String id = resultSet1.getString("id");
                    String type = resultSet1.getString("type");
                    hashMap.put(id, type);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            Set<String> set = hashMap.keySet();
            for (String key : set) {
                String sql2 = "SELECT count(*) AS count FROM loginfo WHERE type = ?";
                try {
                    PreparedStatement preparedStatement = connection.prepareStatement(sql2);
                    preparedStatement.setString(1, key);
                    ResultSet resultSet2 = preparedStatement.executeQuery();
                    String value = hashMap.get(key);
                    int count;
                    if (resultSet2 != null && resultSet2.next()) {
                        count = resultSet2.getInt("count");
                    } else {
                        count = 0;
                    }
                    jsonObject.put(value, count);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            DataBaseConnection.closeConnection(connection);
        }
        return jsonObject.toString();
    }
}
